<template>
    <div>
        <el-dialog :title="props.isAdd ? '商品添加' : '商品编辑'" v-model="props.isShow" center :before-close="beforeClose">
            <el-form :model="goodsForm" label-width="90px" :rules="rules" ref="goodsRef">
                <el-form-item label="一级分类" prop="first_cateid">
                    <el-select @change="changeCate(false)" v-model="goodsForm.first_cateid" placeholder="请选择">
                        <el-option v-for="item in store.getters['cate/getCateList']" :key="item.id" :label="item.catename"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="二级分类" prop="second_cateid" ref="erRef">
                    <el-select v-model="goodsForm.second_cateid" placeholder="请选择">
                        <el-option v-for="item in cateArr" :label="item.catename" :value="item.id" :key="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品名称" prop="goodsname">
                    <el-input v-model="goodsForm.goodsname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input v-model="goodsForm.price" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="市场价格" prop="market_price">
                    <el-input v-model="goodsForm.market_price" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="图片" limit="1" :auto-upload="false">
                    <el-upload action="#" :file-list="fileList" list-type="picture-card" :auto-upload="false"
                        :on-change="onChange" ref="pictureUpload" :limit="1">
                        <el-icon>
                            <Plus />
                        </el-icon>

                        <template #file="{ file }">
                            <div>
                                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                                <span class="el-upload-list__item-actions">
                                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                        <!-- 点击预览 -->
                                        <el-icon><zoom-in /></el-icon>
                                    </span>
                                    <span v-if="!disabled" class="el-upload-list__item-delete">
                                        <el-icon>
                                            <Download />
                                        </el-icon>
                                    </span>
                                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                        <!-- 点击移除 -->
                                        <el-icon>
                                            <Delete />
                                        </el-icon>
                                    </span>
                                </span>
                            </div>
                        </template>
                    </el-upload>
                    <!-- 预览图 -->
                    <el-dialog v-model="dialogVisible">
                        <img class="imgStyle" w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="商品规格" prop="specsid">
                    <el-select @change="changeSpecs(false)" v-model="goodsForm.specsid" placeholder="请选择">
                        <el-option v-for="item in specsList" :key="item.id" :label="item.specsname" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品属性" prop="specsattr">
                    <el-select multiple v-model="goodsForm.specsattr" placeholder="请选择">
                        <el-option v-for="item in specsArr" :label="item" :value="item" :key="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否新品">
                    <el-radio-group v-model="goodsForm.isnew">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="2">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否热卖">
                    <el-radio-group v-model="goodsForm.ishot">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="2">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="goodsForm.status" active-color="#13ce66" inactive-color="#ff4949" :active-value="1"
                        :inactive-value="2">
                    </el-switch>
                </el-form-item>
                <el-form-item label="商品描述">
                    <!-- 富文本编辑器放置到什么位置 -->
                    <!-- <div id="edit"></div> -->
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(goodsRef)">取消</el-button>
                    <el-button type="primary" @click="addBtn(goodsRef)">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { defineProps, ref, reactive, defineEmits, defineExpose } from 'vue'
import type { FormInstance, FormRules, UploadFile } from "element-plus";
import { ElMessage } from "element-plus";
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import store from '@/store';
import { specslist, goodsadd, goodsinfo, goodsedit } from '../../request/api'
// import E from 'wangdeitor';//引入富文本
let newId = 0
//父子传值
let props = defineProps({
    isShow: Boolean,
    isAdd: Boolean
})
let goodsForm = ref<any>({
    first_cateid: "", //一级分类编号
    second_cateid: "", //二级分类编号
    goodsname: "", //商品名称
    price: "", //价格
    market_price: "", //市场价格
    img: "", //图片
    specsid: "", //商品规格
    specsattr: "", //商品属性
    isnew: 1, //是否新品
    ishot: 1, //是否热卖
    status: 1, //状态
    description: "", //商品描述
})
//定义 rules规则 
let rules = reactive<FormRules>({
    first_cateid: [
        { required: true, message: "请选择一级分类名称", trigger: "change" },
    ],
    second_cateid: [
        { required: true, message: "请选择二级分类名称", trigger: "blur" },
    ],
    goodsname: [
        { required: true, message: "请输入商品分类名称", trigger: "blur" },
        { min: 1, max: 8, message: "长度在 1 到 8 个字符", trigger: "blur" },
    ],
    price: [
        { required: true, message: "请输入价格", trigger: "blur" },
    ],
    market_price: [
        { required: true, message: "请输入市场价格", trigger: "blur" },
    ],
    specsid: [
        { required: true, message: "请选择商品规格", trigger: "change" },
    ],
    specsattr: [
        { required: true, message: "请选择商品属性 ", trigger: "blur" },
    ],
});
//单独封装一个关闭X的事件
const beforeClose = (done: any) => {
    done();
    cancel(goodsRef.value);
};
let goodsRef = ref()
//点击取消
let emit = defineEmits(['cancel'])
let cancel = (formEl: FormInstance | undefined) => {
    emit('cancel', false)
    if (!formEl) return//规则验证
    //重置
    goodsForm.value = {
        first_cateid: "", //一级分类编号
        second_cateid: "", //二级分类编号
        goodsname: "", //商品名称
        price: "", //价格
        market_price: "", //市场价格
        img: "", //图片
        specsid: "", //商品规格
        specsattr: "", //商品属性
        isnew: 1, //是否新品
        ishot: 1, //是否热卖
        status: 1, //状态
        description: "", //商品描述
    }
    //清除规则验证
    // formEl.resetFields();
    goodsRef.value.resetFields()//用老方法先
    //清除图片
    fileList.value = []
    //销毁富文本编辑器
    // edit.value.destroy();

}
// 获取列表的行动
store.dispatch('cate/getCatelistActions')//商品分类列表
// store.dispatch('specs/getspecslist')//商品规格列表 只获取第一页的

let cateArr = ref([] as any[])//二级分类数据
let specsList = ref([] as any[])//商品规格列表 因为之前有分页 所以直接使用会不全
let specsArr = ref([] as any[])//商品属性
// 一级分类触发
let changeCate = (e: any) => {
    // console.log(e);
    //筛选出来对应的二级分类列表 可以对比一级列表中的id和数据双向绑定的first_cateid做比较，如果相等就把数组中符合那一项的下标找出来，然后通过该下标就能找到下面的children
    let index = store.getters['cate/getCateList'].findIndex((item: any) => {
        return item.id == goodsForm.value.first_cateid
    })
    // console.log(index);
    //该将数组中的二级列表给cateArr
    cateArr.value = store.getters['cate/getCateList'][index].children
    // console.log(cateArr.value);
    //每次选一级列表清空二级列表数据
    if (!e) {
        goodsForm.value.second_cateid = ''
    }
}
//商品规格触发
let changeSpecs = (e: any) => {
    // console.log(e);
    let index = specsList.value.findIndex((item: any) => {
        return item.id == goodsForm.value.specsid;
    })
    // console.log(index);
    specsArr.value = specsList.value[index].attrs
    if (!e) {
        goodsForm.value.specsattr = ''
    }
}
//获取商品规格 全部
let getSpecslist = () => {
    specslist({}).then((res: any) => {
        console.log(res);
        if (res.code == 200) {
            specsList.value = res.list;
        }
    })
        .catch((err) => {
            console.log(err);
        });
}
getSpecslist()

//点击确定
let addBtn = async (formEl: FormInstance | undefined) => {
    if (!formEl) return//表单验证规则
    await formEl.validate(val => {
        // console.log(val);
        // console.log(goodsForm);
        if (val) {
            console.log(val);

            if (props.isAdd) {
                console.log(1);
                // 添加
                goodsadd(goodsForm.value).then(res => {
                    console.log(res);
                    //调用列表
                    store.dispatch('goods/getgoodslist')
                    store.dispatch('goods/getcount')//获取总条数
                    //隐藏弹框并清空
                    cancel(goodsRef.value)
                    //提示
                    ElMessage({
                        type: 'success',
                        message: res.msg,
                    })
                }).catch(err => {
                    console.log(err);
                })
            } else {
                //编辑
                console.log(2);
                goodsedit({ ...goodsForm.value, id: newId }).then(res => {
                    console.log(res);
                    //调用列表
                    store.dispatch('goods/getgoodslist')
                    store.dispatch('goods/getcount')//获取总条数
                    //隐藏弹框并清空
                    cancel(goodsRef.value)
                    //提示
                    ElMessage({
                        type: 'success',
                        message: res.msg,
                    })
                }).catch(err => {
                    console.log(err);
                })
            }
        }

    })
}
//回显
let lookup = (id: any) => {
    // console.log(id);
    goodsinfo({ id }).then((res: any) => {
        if (res.code == 200) {
            goodsForm.value = res.list
            newId = id
            //图片回显
            fileList.value = goodsForm.value.img ? [{ url: goodsForm.value.img }] : []
            // 由于属性返回字符串，UI库仅支持数组格式
            // console.log(goodsForm.value.specsattr, 333);
            goodsForm.value.specsattr = goodsForm.value.specsattr.split(',');
            //重新触发change事件实现二级联动 不触发导致二级回显是value值
            changeCate(true)
            changeSpecs(true)
        }
    })
}


const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const fileList = ref<any>([])
const pictureUpload = ref()
//文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const onChange = (file: any) => {
    // console.log(file);
    goodsForm.value.img = file.raw//文件信息赋值给数据绑定
}

//移除文件
const handleRemove = (file: UploadFile) => {
    // console.log(file, 1)
    fileList.value = []//清空图片
}

//点击预览
const handlePictureCardPreview = (file: UploadFile) => {
    dialogImageUrl.value = file.url!//预览图赋值
    dialogVisible.value = true//显示预览图
    console.log(1);
}
// let edit = ref()
//富文本封装
// let createEdit = () => {
//     //组件一加载就创建富文本
//     edit.value = new E('#edit');
//     //创建
//     edit.value.create()
//     //初始化
//     // edit.value.text.html(goodsForm.value.description)
//     console.log(edit, '这是富文本');

// }
//导出子组件中的方法
defineExpose({
    lookup
})
</script>
<style lang="less">
.imgStyle {
    width: 400px;
}
</style>